package com.jzoffer2;

import ds.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No07
 * @description
 * @date 2021/2/4 下午2:57
 */
public class No07 {
    public static void main(String[] args) {
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        TreeNode root = buildTree(preorder, inorder);
        System.out.println(root.val);
        System.out.println(root.left.val);
        System.out.println(root.right.val);
    }

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
            return null;
        }
        Map<Integer, Integer> index = new HashMap<>();
        int length = preorder.length;
        // 存放中序元素对应的位置
        for (int i = 0; i < length; i++) {
            index.put(inorder[i],i);
        }
        TreeNode root = buildSubTree(preorder,0,length - 1,inorder,0,length - 1,index);
        return root;
    }

    private static TreeNode buildSubTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> index) {
        if(preStart > preEnd || inStart > inEnd){
            return null;
        }
        int rootVal = preorder[preStart];
        TreeNode root = new TreeNode(rootVal);
        if(preStart == preEnd){
            return root;
        }else{
            int rootIndex = index.get(rootVal);
            int leftNodes = rootIndex - inStart, rightNodes = inEnd - rootIndex;
            TreeNode leftSubtree = buildSubTree(preorder, preStart + 1, preStart + leftNodes, inorder, inStart, rootIndex - 1, index);
            TreeNode rightSubtree = buildSubTree(preorder, preEnd - rightNodes + 1, preEnd, inorder, rootIndex + 1, inEnd, index);
            root.left = leftSubtree;
            root.right = rightSubtree;
            return root;
        }
    }

}
